package com.fit.dao.studentOfTheCourse;

import java.util.List;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.fit.entities.studentOfTheCourse.StudentOfTheCourse;

public class StudentOfTheCourseDAOImpl implements StudentOfTheCourseDAO {

	@Inject
	private Session session;

	@Log
	public boolean save(StudentOfTheCourse newStudentOfTheCourse) {
		if (newStudentOfTheCourse != null) {
			session.save(newStudentOfTheCourse);
			return true;
		}
		return false;
	}

	@Log
	public boolean delete(StudentOfTheCourse studentOfTheCourse) {
		if (studentOfTheCourse != null) {
			session.delete(studentOfTheCourse);
			return true;
		}
		return false;
	}

	@Log
	public boolean update(StudentOfTheCourse studentOfTheCourse) {
		if (studentOfTheCourse != null) {
			session.update(studentOfTheCourse);
			return true;
		}
		return false;
	}

	@Log
	public List findAll() {
		return session.createCriteria(StudentOfTheCourse.class).list();
	}

	@Log
	public boolean deleteByID(Long id) {
		StudentOfTheCourse u = findByID(id);
		if (u != null) {
			delete(u);
			return true;
		}
		return false;
	}

	@Log
	public StudentOfTheCourse findByID(Long id) {
		if (id != null) {
			return (StudentOfTheCourse) session.get(StudentOfTheCourse.class, id);
		}
		return null;
	}

	@Log
	public StudentOfTheCourse findByIdStudentAndIdCourse(int userId, int courseId) {
		if (userId == 0 || courseId == 0) {
			return null;
		}


		List l = session.createCriteria(StudentOfTheCourse.class)
				.add(Restrictions.eq("courseId", courseId))
				.add(Restrictions.eq("id", userId)).list();
		StudentOfTheCourse u = null;
		if (l != null) {
			if (l.size() > 0) {
				u = (StudentOfTheCourse) l.get(0);
			}
		}
		return u;
	}

}
